<template>
  <BottomDrawer
    :visible="addVisible"
    :title="'共享'"
    :width="516"
    @close="addVisible = false"
  >
    <div>
      <el-row>
        <el-col :span="22" :offset="1">
          <PageForm
            ref="pageForm"
            :list="list"
            :form-data="formData"
            :rules="rules"
          >
          </PageForm>
        </el-col>
      </el-row>
    </div>

    <template #footer>
      <el-button type="primary" @click="handleSubmit">确 定</el-button>
      <el-button @click="addVisible = false">取 消</el-button>
    </template>
  </BottomDrawer>
</template>

<script setup lang="ts">
import type { RoleForm, RoleQuery } from '@/types/role';
import type { FormRules, ElTree } from 'element-plus';
import {
  shareTemplate,
  getGroupSelectList,
  cancelShareTemplate,
} from '@/api/formwork/index';
const rules = reactive<FormRules<any>>({
  shareGroupId: [
    { required: true, message: '请选择分享组', trigger: 'change' },
  ],
});
const defaultProps = {
  children: 'children',
  label: 'name',
};

const permissionsId = ref([]);
const emits = defineEmits(['refresh']);
const pageForm = ref();
const filterText = ref('');
const treeRef = ref<InstanceType<typeof ElTree>>();
const directory = ref([]);
watch(filterText, (val) => {
  treeRef.value!.filter(val);
});
const props = defineProps({
  activeName_1: {
    type: String,
    default: '1',
  },
});
defineExpose<{
  open1: (data: any) => void;
}>({
  open1: async (data: any) => {
    addVisible.value = true;
    formData.value = data;
    formData.value.shareGroupSwitch = formData.value.isShare === '0' ? false : true;
    formData.value.shareGroupId = null;
    const ruleFormRef = await getGroupSelectList(data);
    if (ruleFormRef.code == '200') {
      directory.value = ruleFormRef.data.map((item: any) => {
        return {
          ...item,
          label: item.groupName,
          value: item.groupId,
        };
      });
    }
  },
});

const addVisible = ref(false);

const formData = ref<any>({
  templateName: '',
  templateCategory: '',
  templateType: '',
  shareGroupId: null,
  doctorAdvice: '',
  recomScene: '',
  fieldList: [],
  shareGroupSwitch: true,
});

const list: any = computed(() => [
  {
    list: [
      {
        span: 24,
        label: '共享',
        prop: 'shareGroupSwitch',
        component: 'switch',
        labelWidth: '80px',
      },
      {
        span: 24,
        label: '共用目录',
        prop: 'shareGroupId',
        component: 'select',
        labelWidth: '80px',
        hidden: !formData.value.shareGroupSwitch,
        componentProps: {
          placeholder: '请输入共用目录',
          width: '362',
        },
        get selectGroupOptions() {
          return directory.value;
        },
      },
    ],
  },
]);
const handleCheck = () => {
  const checkedNodes = treeRef.value!.getCheckedNodes();
  //console.log(checkedNodes);

  // 直接使用Set来处理formData.value.permissions，确保唯一性
  const parentKeysSet: any = [];
  const parentId: any = [];
  // const parentIdSet: Set<any> = new Set();
  // 遍历勾选的节点
  checkedNodes.forEach((node: any) => {
    // 如果节点有父节点，并且父节点的key不在Set中，则添加到Set中
    if (node.parentId) {
      parentId.push(node.parentId);
      parentKeysSet.push(node.permissionsId);
    }
  });
};
const addDepApi = async () => {
  //console.log(formData.value.shareGroupSwitch);

  shareTemplate(formData.value)
    .then((res) => {
      if (res.code !== '200') {
      
        return;
      }
      ElMessage({
        type: 'success',
        message: '共享成功',
      });
      emits('refresh');
      addVisible.value = false;
    })
    .catch((error) => {
      //console.error('添加失败:', error);
    });
};

const handleSubmit = async () => {
  if (formData.value.shareGroupSwitch === false &&formData.value.isShare==='1') {
    cancelShareTemplate(formData.value)
      .then((res) => {
        if (res.code !== '200') {
          
          return;
        }
        ElMessage({
          type: 'success',
          message: '取消成功',
        });
        emits('refresh');
        addVisible.value = false;
      })
      .catch((error) => {
        //console.error('取消失败:', error);
      });
  } else {
    // cancelShareTemplate
    const ruleFormRef = pageForm.value?.ruleFormRef;
    await ruleFormRef.validate((valid: any, fields: any) => {
      if (valid) {
        addDepApi();
      } else {
        //console.log('error submit!', fields);
      }
    });
  }
};

const getRoleMenu = async () => {};
// 移除空的 onMounted 钩子，避免无意义注册
</script>
<style lang="scss" scoped>
.tree-box {
  border: 2px solid #e1e1e1;
  height: 300px;
  width: 451px;
  margin-top: 10px;
  overflow-y: auto;
}
</style>
